from django.contrib.auth.models import User
from django_redis import get_redis_connection
from rest_framework.serializers import ModelSerializer
from rest_framework_simplejwt.serializers  import TokenObtainSlidingSerializer
from config.dbs.redisconfig import LOGIN_VERIFY_CODE_TEMPLATE


class UserSerializer(ModelSerializer):
    class Meta:
        model = User
        exclude = ['password']



class MyTokenSerializer(TokenObtainSlidingSerializer):
    def validate(self, attrs):
        data = super().validate(attrs)
        token = self.get_token(self.user)
        data['user_id']= self.user.id
        data['username']= self.user.username

        # 图形验证码的校验
        uuid = self.initial_data.get('uuid')
        verify = self.initial_data.get('verify')
        if not uuid or not verify:
            return {'msg':'请输入验证码'}
        cache = get_redis_connection(alias='verify_codes')
        redis_verify = cache.get(LOGIN_VERIFY_CODE_TEMPLATE % uuid)
        cache.delete(LOGIN_VERIFY_CODE_TEMPLATE % uuid)   # 及时释放redis空间
        if not redis_verify:
            return {'msg':'验证码过期'}
        if redis_verify.lower() != verify.lower():
            return {'msg':'验证码错误'}

        return data


class CreateUserSerializer(ModelSerializer):
    class Meta:
        model = User
        fields = ['username', 'first_name', 'email']
        extra_kwargs = {
            'first_name': {
                'required' :True,
            },
            'email':{
                'required' :True,
            }
        }


